<template>
    <div ref="lst" class="my_grid_box" :style="{'grid-template-columns': 'repeat(auto-fit, ' + cellSize + ')','grid-template-rows': 'repeat(auto-fit, auto-fit)'}">
        <slot></slot>
    </div>
</template>

<script>
export default {
    name:"MyGridBox",
    props: {
        columns:{
            type:[String,Number],
            default: 4
        }
    },
    data() {
        return {
            cellSize: 80.75,
            resizeObserver: null,
            width: 0,
        };
    },
    mounted() {
        this.resizeObserver = new ResizeObserver((entries) => {
            const [entry] = entries;
            const { width } = entry.contentRect;
            this.width = width;
            if(typeof(this.columns)=="string"){
                this.cellSize = this.columns;
            }else{
                this.cellSize = ((this.width - this.columns * 8 - 8) / this.columns)+"px";
            }
        });
        this.resizeObserver.observe(this.$refs.lst);
    },
    beforeUnmount() {
        this.resizeObserver.unobserve(this.$refs.lst);
    },
    watch:{
        columns(newVal){
            if(newVal<2){
                newVal = 2;
            }else if(newVal>20){
                newVal = 20;
            }
            this.cellSize = (this.width - newVal * 8 - 8) / newVal;
        }
    }
};
</script>

<style scoped>
.my_grid_box{
    display: grid;
    width: 100%;
    grid-gap: 12px 8px;
    padding:4px;
}
.my_grid_box :deep(img.el-image__inner){
    aspect-ratio:4/3;
}
</style>
